<template>
  <div class="keyword-page">
    <el-card>
      <table-bar :show-top="true" :show-bottom="true" @search="search" @reset="clear">
        <template #top>
          <el-form :inline="true" :model="formInline" class="form-search">
            <el-form-item label="关键词">
              <el-input
                v-model="formInline.search"
                maxlength="20"
                placeholder="请输入关键词"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="add">新增关键词</el-button>
            </el-form-item>
          </el-form>
        </template>
      </table-bar>

      <div class="state-switch">
        <span class="state-label">状态：</span>
        <el-switch
          v-model="value"
          active-color="#3A68F2"
          inactive-color="#dcdfe6"
          active-value="1"
          inactive-value="0"
          @change="changeState"
        />
      </div>

      <art-table
        :data="tableData"
        :loading="tableLoading"
        :border="true"
        :total="total"
        :page="formInline.page"
        :page-size="formInline.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :show-header-background="true"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="keyWord" label="关键词" min-width="150" />
        <el-table-column prop="createTime" label="创建时间" min-width="180" />
        <el-table-column label="操作" fixed="right" width="150" align="center">
          <template #default="scope">
            <button-table type="edit" @click="edit(scope.row)" />
            <el-popconfirm title="确认删除？" @confirm="del(scope.row)">
              <template #reference>
                <button-table type="delete" @click.stop="() => {}" />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </art-table>
    </el-card>

    <!-- 关键词对话框 -->
    <el-dialog
      v-model="isVisible.show"
      :title="isVisible.title"
      width="30%"
      center
      :close-on-click-modal="false"
    >
      <div>
        <el-form ref="formRef" :model="form" label-width="100px">
          <el-form-item label="关键词" prop="keyWord">
            <el-input v-model="form.keyWord" maxlength="20" placeholder="请输入关键词" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="agreeEn" :loading="dialogLoading">确定</el-button>
          <el-button @click="closeDialog">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import {
    wordStart,
    wordGetAll,
    wordAdd,
    wordGetById,
    wordUpdate,
    wordDelete
  } from '@/api/commentApi'
  import {
    Keyword,
    KeywordParam,
    KeywordSaveParam,
    KeywordUpdateParam
  } from '@/api/model/commentModel'
  import { ApiStatus } from '@/utils/http/status'
  import ArtTable from '@/components/Table/ArtTable.vue'
  import TableBar from '@/components/Table/TableBar.vue'
  import ButtonTable from '@/components/Form/ButtonTable.vue'

  const formRef = ref()

  let value = ref('0')
  let formInline = ref<KeywordParam>({
    search: '',
    state: '',
    page: 1,
    pageSize: 10
  })
  let form = ref<KeywordSaveParam>({
    keyWord: '',
    state: 0, // 是否启用 1-是 0-否
    wordId: ''
  })
  let tableLoading = ref(false)
  let dialogLoading = ref(false)
  let isVisible = ref({
    show: false,
    title: '',
    index: 0
  })
  let total = ref(0)
  let tableData = ref<Keyword[]>([])

  onMounted(() => {
    getAll(formInline.value)
  })

  // 获取所有关键词
  async function getAll(params: KeywordParam) {
    try {
      tableLoading.value = true
      const res = await wordGetAll(params)
      if (res.code === ApiStatus.success) {
        tableData.value = res.data?.list || []
        total.value = res.data?.total || 0
      }
    } catch (error) {
      console.error('获取关键词失败:', error)
      ElMessage.error('获取关键词失败')
    } finally {
      tableLoading.value = false
    }
  }

  // 分页大小变化
  function handleSizeChange(val: number) {
    formInline.value.pageSize = val
    getAll(formInline.value)
  }

  // 当前页码变化
  function handleCurrentChange(val: number) {
    formInline.value.page = val
    getAll(formInline.value)
  }

  // 改变状态
  async function changeState(index: string | number | boolean) {
    try {
      dialogLoading.value = true
      const res = await wordStart({ state: index.toString() })
      if (res.code === ApiStatus.success) {
        ElMessage.success('操作成功')
      }
    } catch (error) {
      console.error('修改状态失败:', error)
      ElMessage.error('修改状态失败')
    } finally {
      dialogLoading.value = false
    }
  }

  // 搜索
  function search() {
    total.value = 0
    formInline.value.page = 1
    getAll(formInline.value)
  }

  // 重置
  function clear() {
    formInline.value = {
      search: '',
      state: '',
      page: 1,
      pageSize: 10
    }
    getAll(formInline.value)
  }

  // 添加关键词
  function add() {
    form.value = {
      keyWord: '',
      state: 0,
      wordId: ''
    }
    isVisible.value = {
      show: true,
      title: '添加关键词',
      index: 1
    }
  }

  // 编辑关键词
  async function edit(row: { wordId: any }) {
    try {
      dialogLoading.value = true
      const res = await wordGetById({ wordId: row.wordId })
      if (res.code === ApiStatus.success) {
        form.value = res.data
        isVisible.value = {
          show: true,
          title: '编辑关键词',
          index: 2
        }
      }
    } catch (error) {
      console.error('获取关键词详情失败:', error)
      ElMessage.error('获取关键词详情失败')
    } finally {
      dialogLoading.value = false
    }
  }

  // 确认添加/编辑
  async function agreeEn() {
    if (!form.value.keyWord.trim()) {
      ElMessage.error('请输入关键词')
      return
    }

    try {
      dialogLoading.value = true
      form.value.state = Number(value.value)
      let res
      if (isVisible.value.index === 1) {
        res = await wordAdd(form.value)
      } else {
        // 确保传递正确的类型给wordUpdate
        const updateData: KeywordUpdateParam = {
          wordId: form.value.wordId!,
          keyWord: form.value.keyWord,
          state: form.value.state
        }
        res = await wordUpdate(updateData)
      }

      if (res.code === ApiStatus.success) {
        ElMessage.success('操作成功')
        await getAll(formInline.value)
        closeDialog()
      } else {
        ElMessage.error(res.message || '操作失败')
      }
    } catch (error) {
      console.error('保存关键词失败:', error)
      ElMessage.error('保存关键词失败')
    } finally {
      dialogLoading.value = false
    }
  }

  // 删除关键词
  async function del(row: { wordId: any }) {
    try {
      dialogLoading.value = true
      const res = await wordDelete({ wordId: row.wordId })

      if (res.code === ApiStatus.success) {
        ElMessage.success('删除成功')
        await getAll(formInline.value)
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除关键词失败:', error)
      ElMessage.error('删除关键词失败')
    } finally {
      dialogLoading.value = false
    }
  }

  // 关闭对话框
  function closeDialog() {
    isVisible.value.show = false
  }
</script>

<style lang="scss" scoped>
  .keyword-page {
    padding: 20px;

    .form-search {
      margin-bottom: 15px;
    }

    .state-switch {
      display: flex;
      align-items: center;
      margin-bottom: 20px;

      .state-label {
        margin-right: 10px;
        font-size: 14px;
      }
    }

    // 响应式设计
    @media screen and (max-width: $device-phone) {
      padding: 10px;

      .form-search {
        .el-form-item {
          width: 100%;
          margin-bottom: 10px;

          .el-input {
            width: 50%;
          }
        }
      }

      .state-switch {
        margin-bottom: 15px;
      }

      .el-dialog {
        width: 90% !important;
      }
    }
  }
</style>
